/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package BackupDAO;

import ch.ethz.ssh2.Session;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.faces.context.FacesContext;
import login.bean.LoginBean;

/**
 *
 * @author chucho
 */
public class BackupDAO {

    private LoginBean lb;
    private String user;
    private String pass;
    private String hostServer;
    public Connection conn;

    public BackupDAO() {
        lb = (LoginBean) FacesContext.getCurrentInstance()
                .getExternalContext().getSessionMap().get("loginBean");
        this.conn = lb.getCurrentConnection();
        this.user = lb.getUser();
        this.pass = lb.getPassword();
        this.hostServer = lb.getHost();
    }

    public void executeStatementUpdate(String sql) throws SQLException {
        Statement statement = conn.createStatement();
        statement.executeUpdate(sql);
    }

    public String BackupAllDatabases(String userSSH,
            int portSSH, String passwordSSH, String where) {

        try {
            ch.ethz.ssh2.Connection connect = new ch.ethz.ssh2.Connection(hostServer);
            connect.connect();
            boolean isAuthenticated = connect.authenticateWithPassword(userSSH, passwordSSH);

            if (isAuthenticated == false) {
                throw new IOException("Authentication failed.");
            }
            Session sess = connect.openSession();
            String command = "mysqldump -u " + user +" "+ "-p" + pass + " --all-databases > " + where;
            sess.execCommand(command);
            System.out.println(command);
            try {
                executeStatementUpdate("INSERT INTO  dumps.rutas (ruta) VALUES ('" + where + "');");
                return "BackUp generado Exitosamente";
            } catch (SQLException ex) {
                System.out.println(ex.getLocalizedMessage());
                return ex.getLocalizedMessage();
            }
        } catch (Exception ex) {
            System.out.println(ex.getLocalizedMessage());
            return ex.getLocalizedMessage();
        }
    }
    

    public ResultSet getDumps() throws SQLException {
        String sql = "SELECT * FROM dumps.rutas";
        return conn.createStatement().executeQuery(sql);
    }
}
